#include "oatpp/web/server/HttpConnectionHandler.hpp"
#include "oatpp/network/tcp/server/ConnectionProvider.hpp"
#include "oatpp/network/Server.hpp"

#include "app_components.h"

#include "utils.h"


void run(const char* file_name, std::string& input_ip, uint16_t& input_port) {
  std::string IP = "";
  u_int16_t PORT = 0;

  char delimiter = ':';
  
  // const char* file_name = "config.txt";
  if (is_file_exist(file_name)) {
    std::cout << "[INFO] filename specified" << '\n';
  }
  std::vector<std::string> output;
  if (read_file(output, delimiter, file_name)) {
    IP = output[0];
    PORT = std::stoi(output[1]);
  }

  // for (auto word : output) {
  // }
  if (input_ip != "") { IP=input_ip; }
  if (input_port != 0) { PORT = input_port; }
  std::cout << "[INFO] identify and using IP:PORT = " << IP << ":" << PORT << '\n';

  // 创建 HTTP 请求路由
  auto router = oatpp::web::server::HttpRouter::createShared();
  // 路由 GET 请求到处理程序
  router->route("GET", "/hello", std::make_shared<Handler>());

  // 创建 HTTP 连接
  auto connectionHandler = oatpp::web::server::HttpConnectionHandler::createShared(router);
  // 创建 TCP 连接
  auto connectionProvider = oatpp::network::tcp::server::ConnectionProvider::createShared({
                                // "0.0.0.0", 8000, oatpp::network::Address::IP_4
                                IP, PORT, oatpp::network::Address::IP_4
                            });
  // 创建服务器, 将 TCP 连接传递给 HTTP 处理程序
  oatpp::network::Server server(connectionProvider, connectionHandler);
  // 打印服务器端口
  OATPP_LOGI("web_server", " running on port: %s", connectionProvider->getProperty("port").getData());
  // 运行服务器
  server.run();
}

int main(int argc, char* argv[]) {

  const char* file_name = "";
  std::string input_ip = "";
  uint16_t input_port = 0;

  auto args = parse_args(argc, argv);
  if (args.find("filename") != args.end()) {
    file_name = args["filename"].data();
  }
  if (args.find("ip") != args.end()) {
    std::cout << "[INFO] IP specified" << '\n';
    input_ip = args["ip"].data();
  }
  if (args.find("port") != args.end()) {
    std::cout << "[INFO] PORT specified" << '\n';
    input_port = std::stoi(args["port"].data());
  }
  
  
  // 初始化 oatpp 环境
  oatpp::base::Environment::init();
  // 运行 server
  run(file_name, input_ip, input_port);
  // 销毁 oatpp 环境
  oatpp::base::Environment::destroy();

  return 0;
}